# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import datetime

from flask import request
from flask_restful import reqparse

from ksai.models.document_category import DocumentCategoryModelQuery, DocumentCategoryModel
from ksai.services.document_category import DocumentCategoryService
from ksai.web.api import ApiResource


def parse_app_request(category):
    parser = reqparse.RequestParser()
    parser.add_argument("uuid", type=str, required=False, nullable=True, location="json", )
    parser.add_argument("code", type=str, required=True, nullable=True, location="json", )
    parser.add_argument("name", type=str, required=True, nullable=False, location="json", )
    args = parser.parse_args()

    category.uuid = args['uuid']
    category.code = args['code']
    category.name = args['name']
    return category


class DocumentCategoryController(ApiResource):

    def get(self, query=DocumentCategoryModelQuery()):
        query.init(request.args, 15)
        DocumentCategoryService.find_by_query(query)

        return self.make_success(result=query)

    def post(self):
        category = DocumentCategoryModel()
        category = parse_app_request(category)

        DocumentCategoryService.save(category)
        return self.make_success(category)


class DocumentCategoryUpdateDeleteController(ApiResource):

    def put(self, uuid):
        saved = DocumentCategoryService.find_one_by_uuid(uuid)
        category = parse_app_request(saved)
        category.updated_at = datetime.datetime.now()

        DocumentCategoryService.save(category)

        return self.make_success(category)

    def delete(self, uuid):
        saved = DocumentCategoryService.find_one_by_uuid(uuid)
        saved.deleted_at = datetime.datetime.now()
        DocumentCategoryService.save(saved)
        return self.make_success(saved)
